//
//  AlbumListVC.swift
//  PhotoBrowser
//
//  Created by leotao on 16/5/29.
//  Copyright © 2016年 leotao. All rights reserved.
//

import UIKit
import AssetsLibrary

class AlbumListVC: UITableViewController {
    var dataSource = [ALAssetsGroup]();
    let assetsLibrary = ALAssetsLibrary();
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.tableFooterView = UIView();
        getAlbums();
    }
    
    func getAlbums() {
        assetsLibrary.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { [unowned self](group, _) in
            if group != nil {
                if group.numberOfAssets() > 0 {
                    self.dataSource.append(group);
                }
            } else {
                self.tableView.reloadData();
            }
            }) { (error) in
                print(error);
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataSource.count;
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier = "album";
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? AlbumListCell;
        
        // Configure the cell...
        if cell == nil {
            cell = AlbumListCell(style: .Default, reuseIdentifier: identifier);
        }
        
        cell?.group = self.dataSource[indexPath.row];
//        let group = self.dataSource[indexPath.row];
//        let image = UIImage(CGImage: group.posterImage().takeUnretainedValue());
//        let name = group.valueForProperty(ALAssetsGroupPropertyName) as! String;
//        cell!.configureCell(image, name: name, count: group.numberOfAssets());
//        cell?.group = self.dataSource[indexPath.row];

        return cell!
    }
    
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100;
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let vc = AssetsCollectionViewController();
        vc.assetsGroup = dataSource[indexPath.row];
        self.navigationController?.pushViewController(vc, animated: true);
    }
}
